<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域-->
    <el-card>
      <!--添加角色按钮-->
      <el-button type="success" icon="el-icon-plus" @click="showAddRoleDialogVisible = true">添加角色</el-button>
      <!--用户列表表格渲染区域-->
      <el-table :data="rolesList" border stripe>
        <!--展开列-->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row v-for="(item1, i1) in scope.row.children" :key="item1.id"
                    :class="['bd-bottom', i1 === 0 ? 'bd-top' : '', 'vcenter']">
              <!--渲染一级权限-->
              <el-col :span="5">
                <el-tag @close="removeRightById(scope.row, item1.id)" closable>
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-arrow-right"></i>
              </el-col>
              <!--渲染二级权限-->
              <el-col :span="19">
                <el-row v-for="(item2, i2) in item1.children" :key="item2.id"
                        :class="[i2 === 0 ? '' : 'bd-top', 'vcenter']">
                  <el-col :span="6">
                    <el-tag type="success"
                            @close="removeRightById(scope.row, item2.id)" closable>
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-arrow-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3, i3) in item2.children"
                            :key="item3.id" :class="i3 === 0 ? '' : 'bd-top'"
                            @close="removeRightById(scope.row, item3.id)" closable>
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!--索引列-->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <!--使用插槽渲染操作按钮-->
          <template v-slot="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini"
                       @click="showEditRoleDialog(scope.row.id)">编辑
            </el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini"
                       @click="removeRoleById(scope.row.id)">删除
            </el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini"
                       @click="showAssignRightDialog(scope.row)">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--分配权限的对话框-->
    <el-dialog
        title="分配权限"
        :visible.sync="assignRightDialogVisible"
        width="30%"
        :close-on-click-modal="false">
      <!--内容主体区-->
      <el-form ref="assignRightForm">
        <el-tree
            ref="rightTreeRef"
            :data="rightTree"
            :props="props"
            node-key="id"
            show-checkbox
            default-expand-all
            :default-checked-keys="checkedKeys">
        </el-tree>
      </el-form>
      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
          <el-button @click="assignRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="assignRights">确 定</el-button>
        </span>
    </el-dialog>
    <!--添加角色的对话框-->
    <el-dialog
        title="添加角色"
        :visible.sync="showAddRoleDialogVisible"
        width="30%"
        @close="addRoleDialogClose">
      <el-form ref="addRoleForm" :model="addRoleForm"
               :rules="addRoleFormRules" label-width="80px">
        <el-form-item prop="roleName" label="角色名称">
          <el-input v-model="addRoleForm.roleName" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRoleForm.roleDesc" clearable></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAddRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!--编辑角色的对话框-->
    <el-dialog
        title="编辑角色"
        :visible.sync="showEditRoleDialogVisible"
        width="30%"
        @close="editRoleDialogClose">
      <el-form ref="editRoleForm" :model="editRoleForm"
               :rules="editRoleFormRules" label-width="80px">
        <el-form-item prop="roleName" label="角色名称">
          <el-input v-model="editRoleForm.roleName" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRoleForm.roleDesc" clearable></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
'use strict'
export default {
  name: "Roles",
  data() {
    return {
      rolesList: [],
      // 分配权限对话框的显示
      assignRightDialogVisible: false,
      // 获取到的所有权限数据
      rightTree: [],
      // 权限树节点配置
      props: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的权限数组
      checkedKeys: [],
      // 当前即将分配权限的角色Id
      roleId: '',
      // 添加角色对话框显示
      showAddRoleDialogVisible: false,
      // 添加角色表单实例
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      addRoleFormRules: {
        roleName: [
          {required: true, message: '请输入角色名称', trigger: 'blur'}
        ]
      },
      // 修改角色对话框显示
      showEditRoleDialogVisible: false,
      // 修改角色表单实例
      editRoleForm: {},
      editRoleFormRules: {
        roleName: [
          {required: true, message: '角色名称不能为空', trigger: 'blur'}
        ]
      },
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取所有角色列表
    async getRolesList() {
      const {data: res} = await this.$http.get('roles')

      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data

      // console.log(res.data)
    },
    // 弹窗提示用户是否删除
    async removeRightById(role, rightId) {
      const confirmRes = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const {data: res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.info('删除权限失败')
      }

      role.children = res.data;

      this.$message.success('删除权限成功')
    },
    // 显示分配权限对话框
    async showAssignRightDialog(role) {
      this.roleId = role.id;
      const {data: res} = await this.$http.get('rights/tree')

      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }

      // 将获取到的权限数据保存到 rightTree 中
      this.rightTree = res.data
      // 获取该角色已拥有的权限
      this.checkedKeys = this.getLeafKeys(role, [])
      this.assignRightDialogVisible = true

      console.log(this.rightTree)
    },
    // 通过递归，保存角色下所有三级权限的id，保存到
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
      return arr
    },
    // 点击按钮分配权限
    async assignRights() {
      // ... 展开运算符，用逗号分隔数组内的元素
      const keys = [
        ...this.$refs.rightTreeRef.getCheckedKeys(),
        ...this.$refs.rightTreeRef.getHalfCheckedKeys()]

      // console.log(keys)
      // 将keys数组变成以逗号分隔的字符串
      const idStr = keys.join(',')
      const {data: res} = await this.$http.post(
          `roles/${this.roleId}/rights`, {'rids': idStr})

      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }

      this.$message.success('分配权限成功')
      this.getRolesList()
      this.assignRightDialogVisible = false
    },
    // 关闭添加角色对话框
    addRoleDialogClose() {
      this.$refs.addRoleForm.resetFields()
    },
    // 保存角色信息
    saveRoleInfo() {
      this.$refs.addRoleForm.validate(async valid => {
        if (!valid) return

        const {data: res} = await this.$http.post('roles', this.addRoleForm)

        if (res.meta.status !== 201) {
          return this.$message.error('保存角色失败')
        }

        this.getRolesList()
        this.$message.success('保存角色成功')
        this.showAddRoleDialogVisible = false
      })
    },
    // 按下按钮根据 ID 删除角色
    async removeRoleById(id) {
      const confirmRes = await this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmRes !== 'confirm') {
        return this.$message.info("已取消删除")
      }


      const {data: res} = await this.$http.delete(`roles/${id}`)

      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }

      this.$message.success('删除角色成功')
      this.getRolesList()
    },
    // 显示修改角色对话框
    async showEditRoleDialog(id) {
      const {data: res} = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败')
      }
      this.editRoleForm = res.data

      this.showEditRoleDialogVisible = true
    },
    // 关闭修改角色对话框
    editRoleDialogClose() {
      this.editRoleForm = {}
      this.$refs.editRoleForm.resetFields()
    },
    // 点击按钮修改角色信息
    editRoleInfo() {
      this.$refs.editRoleForm.validate(async valid => {
        if (!valid) return

        const {data: res} = await this.$http.put(
            `roles/${this.editRoleForm.roleId}`,
            this.editRoleForm)

        if (res.meta.status !== 200) {
          return this.$message.error('修改角色信息失败')
        }

        this.$message.success('修改角色信息成功')
        this.getRolesList()
        this.showEditRoleDialogVisible = false
      })
    }
  }
}


</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.vcenter {
  display: flex;
  align-items: center;
}

.bd-top {
  border-top: #eee solid 1px;
}

.bd-bottom {
  border-bottom: #eee solid 1px;
}
</style>